package com.wonders.bigdata.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2021/4/27 10:46
 */
public class PdfToImage {
    public static void main(String[] args) {
        String pdfPath = "C:\\file\\SK2020-082.pdf";
        List<String> images = pdf2jpgSimple(pdfPath);
        for (String image : images) {
            System.out.println(image);
        }

    }

    /**
     * 只是将pdf转换为jpg, 没有其他操作
     * @param pdfFilePath 生成的pdf文件路径包含文件
     * @return
     */
    public static List<String> pdf2jpgSimple(String pdfFilePath) {
        List<String> imageUrls = new ArrayList<>();
        String imageFileSuffix = ".jpg";
        int index = pdfFilePath.lastIndexOf(".");
        String folder = pdfFilePath.substring(0, index);

        try {
            File pdfFile = new File(pdfFilePath);
            PDDocument doc = PDDocument.load(pdfFile);
            int pageCount = doc.getNumberOfPages();
            PDFRenderer pdfRenderer = new PDFRenderer(doc);

            File path = new File(folder);
            if (!path.exists()) {
                path.mkdirs();
            }
            /**
             * imageFilePath是图片生成的最终路径
             */
            String imageFilePath;
            // FIXME: 2019/11/8 这里完成将pdf转换成jpg图片
            for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
                imageFilePath = folder + File.separator + pageIndex + imageFileSuffix;
                BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 105, ImageType.RGB);
                ImageIOUtil.writeImage(image, imageFilePath, 105);
                // FIXME: 2019/12/5 图片路径
                imageUrls.add(imageFilePath);
            }
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageUrls;
    }

    /**

     * 把PDF所有页转换为JPG, 并返回所有图片的路劲集合

     * @param inputFilePath

     * 图片路径,具体到文件名

     * @param outputFilePath

     * 输出目录, 不需要文件名

     * @return

     * @throws IOException

     */

    public static void Pdf2Jpg(String inputFilePath, String outputFilePath) throws IOException {


    }
}
